package com.souku.finance.application.http.retrofit;

import android.text.TextUtils;

import com.souku.finance.application.http.UrlConstact;
import com.souku.finance.application.utils.level.FileUtils;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/8/23.
 */
public class RetrofitUtils {

    /**
     * 1.  noCache  不使用缓存，全部走网络
     * 2.  noStore   不使用缓存，也不存储缓存
     * 3.  onlyIfCached 只使用缓存
     * 4.  maxAge  设置最大失效时间，失效则不使用 需要服务器配合
     * 5.  maxStale 设置最大失效时间，失效则不使用 需要服务器配合
     * 6.  minFresh 设置有效时间，依旧如上
     * 7.  FORCE_NETWORK 只走网络
     * 8.  FORCE_CACHE 只走缓存
     *
     * @return
     */

    private static RequestService requestService;

    public static RequestService create() {
        return create(UrlConstact.Base_Url);
    }

    public static RequestService create(String url) {

        if (requestService != null) {
            return requestService;
        }

        //缓存路径 6142
        String CacheDir = FileUtils.getCacheDir();
        OkHttpClient client;

        if (!TextUtils.isEmpty(CacheDir)) {
            File httpCacheDirectory = new File(CacheDir);
            //缓存容量
            int cacheSize = 10 * 1024 * 1024;
            Cache cache = new Cache(httpCacheDirectory, cacheSize);

            //利用okhttp实现缓存
            client = new OkHttpClient.Builder()
//                .addInterceptor(rewrite_cache_control_interceptor)
//                .addInterceptor(receivedCookiesInterceptor)
//                .addInterceptor(addCookiesInterceptor)
                    .cache(cache)
                    .build();
        }else {
            client = new OkHttpClient.Builder()
//                .addInterceptor(rewrite_cache_control_interceptor)
//                .addInterceptor(receivedCookiesInterceptor)
//                .addInterceptor(addCookiesInterceptor)
                    .build();
        }

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        requestService = retrofit.create(RequestService.class);

        return requestService;
    }

}
